<template>
  <div>
    <div>图片及文件上传阿里云示例</div>
    <p class="tip">
      此处仅是一个代码示例.并不能上传成功，因为我没有购买阿里云，只做项目示例参考。你可以使用修改文件中的配置信息，即可正常使用。功能已使用公司的信息做过测试，可以放心使用。
    </p>
    <div style="margin-top: 20px">
      <p>图片上传</p>
      <el-upload
        class="avatar-uploader"
        action
        multiple="false"
        :show-file-list="false"
        :http-request="httpRequestOrder"
        :on-success="handleSuccess"
      >
        <img v-if="initData.img" :src="initData.img" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </div>

    <div style="margin-top: 20px">
      <p>文件上传</p>
      <el-upload
        :show-file-list="false"
        :http-request="httpRequest"
        :on-success="updateFile"
        accept=".docx"
        name="upfile"
        class="cover-uploader"
        action
      >
        <el-button type="primary" class="fl-left">文件</el-button>
        <span class="file-url fl-left">{{ initData.fileName }}</span>
      </el-upload>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import aliOss from '@/utils/alioss'

const initData = reactive({
  img: '',
  fileName: '',
  fileUrl: ''
})

// 图片上传处理
const httpRequestOrder = (option: any) => {
  aliOss.ossUploadImage(option)
}

// 上传成功回调
const handleSuccess = (response: { imgUrl: string }, file: any) => {
  console.log(response, 'response')
  if (response.imgUrl) {
    initData.img = response.imgUrl
  }
}

// 文件传处理
const httpRequest = (option: any) => {
  aliOss.ossUploadFile(option)
}

// 文件上传成功回调
const updateFile = (res) => {
  if (!res) return
  if (res.name) {
    console.log(res)
    initData.fileName = res.fileName
    initData.fileUrl = res.url
  }
}
</script>

<style lang="scss" scoped>
.tip {
  font-size: 12px;
  color: rgb(80, 79, 77);
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}

.avatar-uploader :hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  width: 148px;
  height: 148px;
  font-size: 28px;
  line-height: 148px;
  color: #8c939d;
  border: 1px dashed #d9d9d9;
}

.avatar {
  display: block;
  width: 146px;
  height: 146px;
}
</style>
